Tutorial Study Image

C++ Files and Streams


June 16, 2023, Learn eTutorial
317

We have been utilizing the iostream standard library up to this point, which offers the cin and cout methods in order to read from the standard input and write to the standard output, respectively.

You will learn how to read and write from files in this tutorial. This requires the fstream library, a standard C++ library that introduces three new data types. That means we are using the fstream standard C++ library to read and write from a file. Let us look at the data types that the fstream library defines:

 

Data Type Description

fstream

It can be used to create new files, write information to the existing files, and read data from existing files.

ifstream

Reading data from files is done using it.

ofstream

This data type is a general-purpose representation of the file stream, and it possesses both ofstream and ifstream functionality, allowing it to create files, write data to them, and read data from them.

File creation and information writing are done using it.

 

The header files <iostream> and <fstream> must be present in your C++ source file if you want to process files in C++.

Opening a File

Before reading from or writing to a file, it needs to be opened. To open a file for writing, you can use either the ofstream or fstream objects. Furthermore, the ifstream object is used to open a file just for reading purposes.

The open() function, a component of the fstream, ifstream, and ofstream objects, has the following syntax.


void open(const char *filename, ios::openmode mode);
 

The open() member function's second parameter, in this case, provides the mode in which the file should be opened, while the first argument, in this case, specifies the name as well as the location of the file that is to be opened.

Mode flag description

ios::app

 

Append mode.

Everything written to that file will be added toward the end.

ios::ate

 

Open a file in order to read.

ios::out

Open a file in order to write.

ios::trunc

Before opening the file, if it already exists, its contents will be shortened.

 

By using the OR operator, you can combine two or more of these variables. For instance, the syntax would be as follows if you wanted to open a file in write mode and truncate it if it was already present.


ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );
 

The following steps can be used to open a file for reading and writing purposes:


fstream  afile;
afile.open("file.dat", ios::out | ios::in );
 

Closing File

The automated flushing of all streams, the release of all memory allotted, and the closing of all open files occur when a C++ program finishes. However, it is always a good practice for a programmer to shut all opened files before terminating a program.

The close() function, a component of the fstream, ifstream, and ofstream objects, has the following

syntax:


void close();
 

Writing into a File

The stream insertion operator (<<) in C++ programming is used to output the information to the screen as well as to send data from your program to a file. The main distinction is that an ofstream or fstream object is used instead of a cout object.

Reading from the File

The stream extraction operator (>>) can be used to input data from the keyboard as well as read data from a file into your program. The cin object is replaced by an ifstream or fstream object, which is the only difference.

An Example for Read and Write

The C++ program that opens a file in reading, as well as writing mode, is provided below. The program reads data from the file and outputs it to the screen after writing user-inputted data to a file called afile.dat.

The C++ program that opens a file in reading, as well as writing mode


#include <fstream>
#include <iostream>
using namespace std;
 
int main () {
   char data[100];

   // open a file in the write mode.
   ofstream outfile;
   outfile.open("afile.dat");

   cout << "Just Writing to the file" << endl;
   cout <<"Can you please enter your name: "; 
   cin.getline(data, 100);

   // write inputted data into the file.
   outfile << data << endl;

   cout << "Please enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // again write the  inputted data into the file.
   outfile << data << endl;

   // just close the opened file.
   outfile.close();

   // open a file in the read mode.
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 

   // write the data on the screen.
   cout << data << endl;
   
   // again read the data from the file as well as display it.
   infile >> data; 
   cout << data << endl; 

   //just close the opened file.
   infile.close();

   return 0;
}

 

Output:


Just Writing to the file
Can you please enter your name: MeghnaMariya
Please enter your age: 23
Reading from the file
MeghnaMariya
23

The preceding examples make use of additional cin object functions, such as the getline() function in order to read the line from the outside as well as the ignore() function in order to ignore the excess characters left by the previous read command.

Pointers for File Position

The file-position pointer can be moved using the member functions offered by both istream as well as the ostream. These member functions are seekg ("seek get") as well as the seekp ("seek put") for istream and ostream, respectively.

Ordinarily, a long integer is used as the parameter to seekg and seekp. To specify the seek direction, a second input can be provided. The seek direction can be one of three options: ios::beg (the default) for positioning relative to a stream's starting, ios::cur for positioning relative to a stream's current location, or ios::end for positioning related to a stream's end.

An integer value known as a file-position pointer indicates a place within a file as a number of bytes from the file's beginning location. The following are some instances of where to position the "get" file-location pointer:


//The  position mainly to the nth byte of fileObject (assumes ios::beg)
fileObject.seekg( n );

// The position of the  n bytes forward in fileObject
fileObject.seekg( n, ios::cur );

//The  position n bytes back from the  end of fileObject
fileObject.seekg( n, ios::end );

// The position mainly at end of fileObject
fileObject.seekg( 0, ios::end );

 

Let's have a look at the straightforward C++ FileStream programming example of writing to the text file testout.txt.

Example of a C++ FileStream: writing into a file


#include <iostream>  
#include <fstream>  
using namespace std;  
int main () {  
  ofstream filestream("testout.txt");  
  if (filestream.is_open())  
  {  
    filestream << "Welcome to learnEtutorials.\n";  
    filestream << "The C++ Tutorial.\n";  
    filestream.close();  
  }  
  else cout <<"File opening is a fail.";  
  return 0;  
}  

 

Output:


Welcome to learnEtutorials
The C++ Tutorial